package edu.hit.stu.filter;

import edu.hit.stu.util.common.IPrint;
import edu.hit.stu.util.jwt.JwtProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class JwtFilter implements WebFilter {

    private final JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst(jwtProperties.getHeader());
        if (checkJwtToken(token)) {
            exchange.getRequest().mutate()
                    .headers(httpHeaders -> {
                        String trim = httpHeaders.getFirst(jwtProperties.getHeader()).replace("Bearer ", "");
                        httpHeaders.set(jwtProperties.getHeader(), trim);
                    }).build();
        } else {
            IPrint.printWithColor("JWT 不存在 或者 不合法");
        }
        return chain.filter(exchange);
    }

    /**
     * <ul>
     *   <li>检查 请求体 - 是否含有令牌</li>
     *   <li>请求体中 - 令牌格式是否正确</li>
     * </ul>
     * @param header 请求体头部
     * @return 正确: true <br/>错误: false
     */
    private boolean checkJwtToken(String header) {
        if (header != null && header.startsWith(jwtProperties.getPrefix())) {
            return true;
        } else {
            return false;
        }
    }

/*    protected Mono<Void> writeErrorMessage(ServerHttpResponse response, HttpStatus status, String msg) throws JsonProcessingException, UnsupportedEncodingException {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ObjectMapper mapper=new ObjectMapper();
        String body = mapper.writeValueAsString(new HttpResult(status.value(), msg, null));
        DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }*/
}
